package com.freecloud.whispered.email.service.impl;

import cn.hutool.core.util.StrUtil;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.framework.utils.MailUtil;
import com.freecloud.whispered.message.entity.Message;
import com.freecloud.whispered.message.service.MessageService;
import com.freecloud.whispered.auth.entity.SysUserEntity;
import com.freecloud.whispered.auth.service.SysUserCallFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Author: maomao
 * @Date: 2019-08-29 10:13
 */
@Service
public class EmailServiceImpl implements MessageService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysUserCallFactory sysUserCallFactory;

    @Override
    public boolean send(Message message) {

        if(StrUtil.isBlank(message.getUserId())){
            throw new RRException("收件用户不能为空！");
        }
        SysUserEntity sysUserEntity = sysUserCallFactory.call().queryUserById(Long.valueOf(message.getUserId()));

        if(sysUserEntity == null || StrUtil.isBlank(sysUserEntity.getEmail())){
            throw new RRException("未知用户或用户未设置邮箱地址！");
        }
        return MailUtil.sendMail(sysUserEntity.getEmail(), message.getTitle(), message.getContent(), true, null);
    }

    @Async("free-cloud-thread")
    @Override
    public void asyncSend(Message message) {
        logger.info("异步发送邮件：{}",message);
        send(message);
    }
}
